﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

using IsmlTools.Common;
using IsmlTools.Dal.SQL;
using System.Data.Entity;

using log4net;
using log4net.Config;
using log4net.Util;

namespace IsmlTools.Common
{
    public class NameHelper
    {
        private ILog log = LogManager.GetLogger(typeof(NameHelper));

        public Dictionary<string, string> GetSeasonName(ISMLEntities db, int seasonID)
        {
            try
            {
                var query = db.SeasonNames.Where(x => x.SeasonID == seasonID);

                return query.ToDictionary(seasonname => seasonname.NameCode, seasonname => seasonname.English);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("GetSeasonName() failed. seasonID: " + seasonID + " Details: " + ex.GetBaseException().Message);
                return null;
            }

        }

        public Dictionary<int, string> GetSeasonName(string url, string language)
        {
            Dictionary<int, string> name = new Dictionary<int, string>();
            WebHelper webhelper = new WebHelper();

            // 没用了？
            name.Clear();
            string page = webhelper.ReadPage(url);

            //languageCode = language;
            page = page.Replace("\")\n}", "\"###\n}");
            page = page.Replace("\")\r\n}", "\"###\r\n}");
            page = page.Replace("),", "###");
            page = page.Replace("\"", "");
            page = page.Replace("フィン・エ・ルド・スイ・ラフィンティ, ラン", "フィン・エ・ルド・スイ・ラフィンティ(ラン)");


            //string s = RegHelper.GetMidPattern(language + @" : Array\(", "###");
            Regex reg = new Regex(RegHelper.GetMidPattern(language + @"[ ]+?: Array\(", "###"));
            Regex reg1 = new Regex(RegHelper.GetMidPattern("var nList", @" \= \{"));

            MatchCollection mc = reg.Matches(page);
            MatchCollection mc1 = reg1.Matches(page);

            try
            {
                for (int i = 0; i < mc.Count; i++)
                {
                    if (!mc[i].Value.Equals("{}") && !mc[i].Value.Equals(string.Empty))
                    {
                        string[] lines = Regex.Split(mc[i].Value, ",");
                        int num = 0;
                        num = i < mc.Count - 2 ? int.Parse(mc1[i / 2].Value) + 1 : 1;

                        for (int j = 0; j < lines.Length; j++)
                        {
                            if (!name.ContainsKey(num + j))
                                name.Add(num + j, Regex.Replace(lines[j], @"[‧•・]", "·"));
                        }
                    }
                    i++;
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("GetSeasonName() failed. url:" + url +" Details: " + ex.GetBaseException().Message);
            }

            return name;
        }

        public void SaveSeasonName(string url, int seasonID)
        {
            Dictionary<int, string> name = new Dictionary<int, string>();
            //WebHelper webhelper = new WebHelper();

            //string page = webhelper.ReadPage(WebPageLink.NamesSeason);

            foreach (string language in LanguageCode.AllLanguage)
            {
                name = GetSeasonName(url, language);

                try
                {
                    using (ISMLEntities db = new ISMLEntities())
                    {
                        foreach (var v in name)
                        {
                            string temp = v.Key.ToString();
                            var query = db.SeasonNames.FirstOrDefault(x => x.SeasonID == seasonID && x.NameCode == temp);
                            if (query == null)
                            {
                                if (language == LanguageCode.En)
                                {
                                    SeasonName seasonname = new SeasonName { SeasonID = seasonID, NameCode = v.Key.ToString(), English = v.Value.Trim()};
                                    db.SeasonNames.Add(seasonname);
                                }                               
                            }
                            else
                            {
                                switch (language)
                                {
                                    case LanguageCode.Sc:
                                        query.SimplifiedChinese = v.Value.Trim();
                                        break;
                                    case LanguageCode.En:
                                        query.English = v.Value.Trim();
                                        break;
                                    case LanguageCode.Jp:
                                        query.Japanese = v.Value.Trim();
                                        break;
                                    case LanguageCode.Kr:
                                        query.Korean = v.Value.Trim();
                                        break;
                                    case LanguageCode.Ru:
                                        query.Russian = v.Value.Trim();
                                        break;
                                    case LanguageCode.Tc:
                                        query.TraditionalChinese = v.Value.Trim();
                                        break;
                                }
                            }
                        }
                        db.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    log.ErrorFormat("SaveSeasonName() failed. url:" + url + " Details: " + ex.GetBaseException().Message);
                }
            }
        }
    }
}
